package cn.seaboot.word.html;

import cn.seaboot.commons.core.CommonUtils;
import cn.seaboot.commons.core.Tokenizer;
import cn.seaboot.commons.file.Base64ImageUtils;
import cn.seaboot.html.HtmlReader;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

/**
 * 文本区域的内容读取
 * <p>
 * 一个段落，包含多个的文本区域，文本区域中，包含：图片、文字
 *
 * @author Mr.css
 * @version 2025-06-26 14:37
 */
public class RunReader implements HtmlReader<XWPFRun> {

    /**
     * 结果写出
     */
    private final Writer writer;

    public RunReader(Writer writer) {
        this.writer = writer;
    }

    @Override
    public void read(XWPFRun run) throws IOException {
        // read text
        String text = run.text();
        if (CommonUtils.isNotEmpty(text)) {
            writer.write("<span>");
            writer.write(text);
            writer.write("</span>\r\n");
        }

        // read picture
        List<XWPFPicture> pictures = run.getEmbeddedPictures();
        if (CommonUtils.isNotEmpty(pictures)) {
            for (XWPFPicture picture : pictures) {
                XWPFPictureData data = picture.getPictureData();
                String src = Base64ImageUtils.bytesToBase64Url(data.getData());
                String name = data.getFileName();
                String tpl = "<img src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" />";
                String html = Tokenizer.replace(tpl, src, name, picture.getWidth(), picture.getDepth());
                writer.write(html);
            }
        }
    }
}
